// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const TcbRouter = require('tcb-router')
const db = cloud.database()
const blogCollection = db.collection('blog')
const MAX_LIMIT = 100

// 云函数入口函数
exports.main = async(event, context) => {
  const app = new TcbRouter({
    event
  })

  app.router('list', async(ctx, next) => {
    const keyword = event.keyword
    let w = {}
    if (keyword.trim() != '') {
      w = {
        content: new db.RegExp({
          options: 'i',
          regexp: keyword
        })
      }
    }
    let blogList = await blogCollection.where(w).skip(event.start).limit(event.count)
      .orderBy('creatTime', 'desc').get().then((res) => {
        return res.data
      })
    ctx.body = blogList
  })

  app.router('detail', async(ctx, next) => {
    const blogId = event.blogId
    // 详情查询
    let detail = await blogCollection.where({
      _id: blogId
    }).get().then((res) => {
      return res.data
    })

    // 评论查询
    let result = await blogCollection.count()
    let total = result.total
    let blogComment = {
      data: []
    }
    if (total > 0) {
      let batch_times = Math.ceil(total / MAX_LIMIT)
      let tasks = []
      for (let i = 0; i < batch_times; i++) {
        let promise = await db.collection('blog-comment')
          .skip(i * MAX_LIMIT).limit(MAX_LIMIT).where({
            blogId
          }).orderBy('creatTime', 'desc').get()
        tasks.push(promise)
      }
      if (tasks.length > 0) {
        blogComment = (await Promise.all(tasks)).reduce((acc, cur) => {
          return {
            data: acc.data.concat(cur.data)
          }
        })
      }

    }
    ctx.body = {
      detail,
      blogComment,
    }
  })
  const wxContext = cloud.getWXContext()
  app.router('getMyBlogList', async(ctx, next) => {
    ctx.body = await blogCollection.where({
        _openid: wxContext.OPENID
      }).skip(event.start).limit(event.count)
      .orderBy('creatTime', 'desc').get().then((res) => {
        return res.data
      })
  })

  return app.serve()
}